﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.IO;

namespace mitasoft.ExcelHelper
{
    public class Engine
    {
        private Worksheet ws = null;

        public Worksheet NewWorksheet()
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                throw new Exception("EXCEL could not be started. Check that your office installation and project references are correct.");
            }
            xlApp.Visible = true;

            Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet ws = (Worksheet)wb.Worksheets[1];

            if (ws == null)
            {
                throw new Exception("Worksheet could not be created. Check that your office installation and project references are correct.");
            }

            return ws;
        }
        public Worksheet OpenWorksheet(string fileName)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                throw new Exception("EXCEL could not be started. Check that your office installation and project references are correct.");
            }
            xlApp.Visible = true;

            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates\\" + fileName);

            Workbook wb = xlApp.Workbooks.Open(filePath);
            Worksheet ws = (Worksheet)wb.Worksheets[1];

            if (ws == null)
            {
                throw new Exception("Worksheet could not be found. Check that your office installation and project references are correct.");
            }

            return ws;
        }
    }

    public static class ExcelExtensions
    {

        public static Range GetCell(this Worksheet worksheet, int rowIndex, int colIndex)
        {
            return worksheet.Cells[rowIndex, colIndex];
        }

        public static void WriteToExcel(this Worksheet worksheet, Func<IEnumerable<Cell>> cells)
        {
            var ws = worksheet;

            if (cells == null)
            {
                throw new Exception("Please provide the cells you want to write.");
            }

            foreach (var cell in cells())
            {
                var currentCell = ws.Cells[cell.RowIndex, cell.ColIndex];

                if (cell.MakeAs != null)
                {
                    cell.MakeAs.Copy(currentCell);
                }

                currentCell.Value = cell.Value;
            }
        }
    
    }

}
